package com.zhongen.oa.service.impl;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.zhongen.oa.entity.AccessToken;
import com.zhongen.oa.entity.TemplateMessage;
import com.zhongen.oa.entity.WeChatTemplateMsg;
import com.zhongen.oa.task.WXPublicAccountHttpUtil;
import com.zhongen.quartz.util.WxMpProperties;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@AllArgsConstructor
public class WxServlet extends HttpServlet {

    // 必须替换
    private static final String wxToken = "xxxxxm8";
    // 必须替换
    public static final String APPID = "wx3xxxxxx1795fa";
    // 必须替换
    public static final String SECRET = "57b96fxxxxxxxxeab62bfe3";
    // 必须替换
    public static final String MESSAGE_TEMPLATE_ID = "N6MyyAF0Ucxxxxxxxxxxxxxxxxp-OGsWnQut_niUAaY";

	private final WxMpProperties wxMpProperties;
    /**
     * 全局AccessToken
     */
    private static AccessToken at;
/*
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        if ("/wx".equals(request.getServletPath())) {
            doGetWx(request, response);
        } else if ("/wx/message".equals(request.getServletPath())) {
            doSendMessage(request, response);
        }

    }*/

//    /**
//     * @Description 校验配置URL服务器的合法性
//     * @date 2023年5月29日下午4:17:40
//     * @param request
//     * @param response
//     * @throws ServletException
//     * @throws IOException
//     */
    public void doGetWx(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        // 将微信echostr返回给微信服务器
        try (OutputStream os = response.getOutputStream()) {
            String sha1 = getSHA1(wxToken, timestamp, nonce, "");

            // 和signature进行对比
            if (sha1.equals(signature)) {
                // 返回echostr给微信
                os.write(URLEncoder.encode(echostr, "UTF-8").getBytes());
                os.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


   /**
     * @Description 发送模板消息
     * @date 2023年5月30日上午10:57:45
     * @param request
     * @param response
     * @throws IOException
     */
    private void doSendMessage(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String token = getToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?" + "access_token=" + token;
        // 获取 openid 数组
        List<String> userOpenids = WXPublicAccountHttpUtil.getOpenidList(url);


        // 主要的业务逻辑：
        for (String openId : userOpenids) {
//            TemplateMessage templateMessage = new TemplateMessage();
//            templateMessage.setTouser(openId);
//            templateMessage.settemplate_id(wxMpProperties.getTemplateId());
//            templateMessage.setTopcolor("#FF0000");
//
//            // key对应创建模板内容中的形参
//            //{{title.DATA}} {{username.DATA}} {{quote.DATA}} {{date.DATA}}
//            // WeChatTemplateMsg对应实参和字体颜色
//            Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
//            data.put("title", new WeChatTemplateMsg("测试", "#173177"));
//            data.put("username", new WeChatTemplateMsg("黄先生", "#173177"));
//            data.put("date", new WeChatTemplateMsg("2023年05月29日 16时24分", "#173177"));
//            data.put("quote", new WeChatTemplateMsg("你好", "#173177"));
//
//
//            templateMessage.setData(data);
//
//            System.out.println(templateMessage);
//
//            WXPublicAccountHttpUtil.sendMessage(getToken(), templateMessage);

        }

    }

    /**
     * @Description 发送模板消息
     * @date 2023年5月30日上午10:57:45
     * @throws IOException
     */
    public void doSendMessage() throws IOException {

        String token = getToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?" + "access_token=" + token;
        // 获取 openid 数组
        List<String> userOpenids = WXPublicAccountHttpUtil.getOpenidList(url);


        // 主要的业务逻辑：
        for (String openId : userOpenids) {
			System.err.println(openId);
//            TemplateMessage templateMessage = new TemplateMessage();
//            templateMessage.setTouser(openId);
//            templateMessage.settemplate_id(wxMpProperties.getTemplateId());
//            templateMessage.setTopcolor("#FF0000");
//
//            // key对应创建模板内容中的形参
//            //{{title.DATA}} {{username.DATA}} {{quote.DATA}} {{date.DATA}}
//            // WeChatTemplateMsg对应实参和字体颜色
//            Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
//            data.put("title", new WeChatTemplateMsg("你有一条新的消息", "#173177"));
//            data.put("username", new WeChatTemplateMsg("黄先生", "#173177"));
//            data.put("date", new WeChatTemplateMsg("2023年05月29日 16时24分", "#173177"));
//            data.put("quote", new WeChatTemplateMsg("你好", "#173177"));
//
//
//            templateMessage.setData(data);
//
//            System.out.println(templateMessage);
//
//            WXPublicAccountHttpUtil.sendMessage(getToken(), templateMessage);

        }

    }

    /**
     * @Description 发送模板消息
     * @date 2023年5月30日上午10:57:45
     * @throws IOException
     */
    public List<String> testSendMessage() throws IOException {

        String token = getToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/get?" + "access_token=" + token;
        // 获取 openid 数组
        List<String> userOpenids = WXPublicAccountHttpUtil.getOpenidList(url);

//		TemplateMessage templateMessage = new TemplateMessage();
//		templateMessage.setTouser("on4UX1d7kjQq5OFzTruAtNh63eK8");
//		templateMessage.settemplate_id(wxMpProperties.getTemplateId());
//		templateMessage.setTopcolor("#FF0000");
//
//		// key对应创建模板内容中的形参
//		//{{title.DATA}} {{username.DATA}} {{quote.DATA}} {{date.DATA}}
//		// WeChatTemplateMsg对应实参和字体颜色
//		Map<String, WeChatTemplateMsg> data = new HashMap<String, WeChatTemplateMsg>();
//		data.put("title", new WeChatTemplateMsg("你有一条新的消息", "#173177"));
//		data.put("username", new WeChatTemplateMsg("黄先生", "#173177"));
//		data.put("date", new WeChatTemplateMsg("2023年05月29日 16时24分", "#173177"));
//		data.put("quote", new WeChatTemplateMsg("你好", "#173177"));
//
//
//		templateMessage.setData(data);
//
//		System.out.println(templateMessage);
//
//		WXPublicAccountHttpUtil.sendMessage(getToken(), templateMessage);

		return userOpenids;

    }

    /**
     * @Description 获取token, 本地缓存有就直接返回，没有就发送请求获取（wx官方api获取token每天有限制，因此需做缓存)
     * @date 2023年5月29日下午4:13:17
     * @return
     */
    public String getToken() {
        if (at == null || at.isExpired()) {
            getAccessToken();
        }
        return at.getAccessToken();
    }

    /**
     * 给AccessToken赋值
     */
    private void getAccessToken() {

        // 发送请求获取token
        String token = null;
        try {
            String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"+ "&appid=" + wxMpProperties.getAppid() + "&secret=" + wxMpProperties.getSecret();
            token = WXPublicAccountHttpUtil.get(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(token);
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        // 创建token对象，并存储
        at = new AccessToken(accessToken, String.valueOf(expiresIn));
        System.out.println(token);

    }


    /**
     * 用SHA1算法生成安全签名
     *
     * @param token     票据
     * @param timestamp 时间戳
     * @param nonce     随机字符串
     * @param encrypt   密文
     * @return 安全签名
     * @throws Exception
     */
    public static String getSHA1(String token, String timestamp, String nonce, String encrypt) throws Exception {
        try {
            String[] array = new String[] { token, timestamp, nonce, encrypt };
            StringBuffer sb = new StringBuffer();
            // 字符串排序
            Arrays.sort(array);
            for (int i = 0; i < 4; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            // SHA1签名生成
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(str.getBytes());
            byte[] digest = md.digest();
            StringBuffer hexstr = new StringBuffer();
            String shaHex = "";
            for (int i = 0; i < digest.length; i++) {
                shaHex = Integer.toHexString(digest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexstr.append(0);
                }
                hexstr.append(shaHex);
            }
            return hexstr.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
